import { memo, useEffect, useState } from "react";
import { VideoWrapper, ScaleWrapper } from "./style";
import SearchItems, {
  type ISearchFormItem,
} from "../../../commponts/SearchItems";
import {
  IconEdit,
  IconDelete,
  IconDownload,
  IconPlus,
} from "@arco-design/web-react/icon";
import { useAppDispatch, useAppSelector } from "../../../store";
import {
  fetchDeleteVideoAction,
  fetchGetVedioAction,
} from "../../../store/modules/video";
import { Button, Message, Modal, Popover, Table } from "@arco-design/web-react";
import { mapState } from "../../../utils/mapState";
import ModalPage from "./Modal";

const VideoPage = () => {
  const dispatch = useAppDispatch();
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSzie] = useState(10);
  const [isVideo, setIsVideo] = useState(false);
  const [currentVideoUrl, setCurrentVideoUrl] = useState<string>("");
  const [visible, setVisible] = useState(false);
  const [mode, setMode] = useState<"edit" | "add">("edit");
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [currentId, setCurrentId] = useState<number | null>(null);
  const [isDelete, setIsDelete] = useState(false);
  const [searchParams, setSearchParams] = useState<{
    videoTitle: string | null;
    department: string | null;
    state: string;
  }>({ videoTitle: "", department: "", state: "" });
  const { videoList, total } = useAppSelector((state) => state.video);
  const searchItems: ISearchFormItem[] = [
    {
      type: "input",
      field: "videoTitle",
      label: "视频标题",
      placeholder: "请输入视频标题",
    },
    {
      type: "input",
      field: "department",
      label: "发布单位",
      placeholder: "请输入发布单位",
    },
    {
      type: "select",
      field: "state",
      label: "发布状态",
      placeholder: "请选择状态",
      options: [
        {
          label: "已发布",
          value: "1",
        },
        {
          label: "未发布",
          value: "0",
        },
      ],
    },
  ];

  const fetchVideoList = async () => {
    await dispatch(
      fetchGetVedioAction({
        pageNum,
        pageSize,
      })
    );
  };
  useEffect(() => {
    fetchVideoList();
  }, [dispatch, pageNum, pageSize]);

  const columns = [
    {
      title: "视频id",
      dataIndex: "id",
    },
    {
      title: "视频标题",
      dataIndex: "videoTitle",

      render: (value: string) => {
        return (
          <Popover content={value}>
            <span className="title">{value}</span>
          </Popover>
        );
      },
    },
    {
      title: "视频",
      dataIndex: "video",

      render: (value: string) => {
        return (
          <Button
            type="text"
            onClick={() => {
              setCurrentVideoUrl(value);
              setIsVideo(true);
            }}
          >
            播放视频
          </Button>
        );
      },
    },
    {
      title: "发布单位",
      dataIndex: "department",
    },
    {
      title: "视频名称",
      dataIndex: "fileName",
      render: (value: string) => {
        return value ? <span>{value}</span> : <span>暂未命名</span>;
      },
    },
    {
      title: "发布状态",
      dataIndex: "state",

      render: (value: string) => {
        if (value === "1") return <span>已发布</span>;
        else return <span>未发布</span>;
      },
    },
    {
      title: "操作",
      dataIndex: "movement",

      render: (value: any, record: any) => {
        // console.log(record);
        return (
          <div>
            <Button
              type="text"
              icon={<IconEdit />}
              onClick={() => {
                setSelectedRowKeys([record.id]);
                setMode("edit");
                setCurrentId(record.id);
                setVisible(true);
              }}
            >
              修改
            </Button>
            <Button
              type="text"
              icon={<IconDelete />}
              onClick={() => {
                setSelectedRowKeys([record.id]);
                setIsDelete(true);
              }}
            >
              删除
            </Button>
          </div>
        );
      },
    },
  ];
  const data = videoList?.map((item) => {
    return {
      id: item.id,
      videoTitle: item.title,
      video: item.video,
      department: item.department,
      fileName: item.fileName,
      state: item.state,
    };
  });
  const filterDate = data?.filter((item) => {
    const matchTitle =
      !searchParams.videoTitle ||
      item?.videoTitle?.includes(searchParams.videoTitle);
    const matchDept =
      !searchParams.department ||
      item?.department?.includes(searchParams.department);
    const matchState =
      !searchParams.state ||
      item.state === String(mapState(searchParams.state));
    return matchState && matchDept && matchTitle;
  });
  const onSearch = (values: any) => {
    setSearchParams(values);
    console.log(values);
  };
  //*选择框逻辑
  const onSelectChange = (newSelectedRowKeys: any[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // console.log(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  function onClose() {
    setVisible(false);
    setSelectedRowKeys([]);
  }
  function handleEdit() {
    setMode("edit");
    setCurrentId(Number(selectedRowKeys[selectedRowKeys.length - 1]));
    setVisible(true);
  }
  function handleAdd() {
    setMode("add");
    setCurrentId(null);
    setVisible(true);
  }

  const deleteVeido = async () => {
    await dispatch(fetchDeleteVideoAction(selectedRowKeys));
    setIsDelete(false);
    setSelectedRowKeys([]);
    Message.success("删除成功");
    fetchVideoList();
  };
  return (
    <VideoWrapper>
      <Modal
        title="播放视频"
        onOk={() => setIsVideo(false)}
        visible={isVideo}
        onCancel={() => setIsVideo(false)}
      >
        {currentVideoUrl ? (
          <video
            src={currentVideoUrl}
            controls
            autoPlay
            style={{ width: "100%", borderRadius: "8px" }}
          />
        ) : (
          <p>暂无视频</p>
        )}
      </Modal>
      <Modal
        title="警告"
        onCancel={() => {
          setIsDelete(false);
          setSelectedRowKeys([]);
        }}
        onOk={deleteVeido}
        visible={isDelete}
      >
        <p style={{ textAlign: "center" }}>
          你确定要删除id为{selectedRowKeys.join(",")}的文章吗？
        </p>
      </Modal>
      <ModalPage
        visible={visible}
        id={currentId}
        onClose={onClose}
        mode={mode}
        onRefresh={fetchVideoList}
      />
      <SearchItems items={searchItems} onSearch={onSearch}></SearchItems>

      <div className="centerWrapper">
        <Button
          icon={<IconPlus />}
          type="primary"
          onClick={handleAdd}
          className="btn"
        >
          新增
        </Button>
        <Button
          icon={<IconEdit />}
          type="primary"
          status="success"
          className="btn"
          onClick={handleEdit}
          disabled={selectedRowKeys.length < 1}
        >
          修改
        </Button>
        <Button
          disabled={selectedRowKeys.length < 1}
          className="btn"
          icon={<IconDelete />}
          type="primary"
          status="danger"
          onClick={() => {
            setIsDelete(true);
          }}
        >
          删除
        </Button>
        <Button
          className="btn"
          icon={<IconDownload />}
          type="primary"
          status="warning"
          onClick={() => {
            Modal.warning({
              title: "通知",
              content: "导出接口崩了，正在维修中。。。",
              okText: "关闭",
            });
          }}
        >
          导出
        </Button>
      </div>

      <div className="table">
        <Table
          rowKey={(record) => record.id}
          rowSelection={rowSelection}
          columns={columns}
          data={filterDate}
          style={{ userSelect: "none", tableLayout: "fixed" }}
          pagination={{
            total,
            sizeOptions: [10, 20, 30],
            showJumper: true,
            pageSize,
            current: pageNum,
            showTotal: (total) => `共${total}条`,
            sizeCanChange: true,
            onChange: (current, pageSize) => {
              setPageNum(current);
              setPageSzie(pageSize);
            },
            style: {
              marginRight: "15px",
            },
          }}
        />
      </div>
    </VideoWrapper>
  );
};
export default memo(VideoPage);
